#include <bits/stdc++.h>
using namespace::std;

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candys(ratings.size(), 1);

        // 向右遍历，确保满足左规则 - 不能向右遍历满足右规则，因为向右遍历会修改右值，导致前面不满足右规则
        for(int i = 1; i < ratings.size(); ++i){
            if(ratings[i] > ratings[i - 1]) candys[i] = candys[i - 1] + 1;
        }

        for(int i = ratings.size() - 2; i >= 0; --i){
            if(ratings[i] > ratings[i + 1] && candys[i] <= candys[i + 1]) candys[i] = candys[i + 1] + 1;
        }

        int sum = 0;
        for(int i = 0; i < ratings.size(); ++i)
            sum += candys[i];
        return sum;
    }
};

int main(int argc, char const *argv[])
{
    Solution sol;

    vector<int> ratings = {1,3,4,5,2};

    cout << sol.candy(ratings) << endl;

    return 0;
}
